﻿using AutoMapper;
using PagedList;
using SIG.DAL.Dapper.Model;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Products;
using SIG.Model.LuceneSearch;
using SIG.Resources.Admin;
using SIG.Service.LuceneSearch;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Products;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    public class TechnologyController : BaseController
    {

        private readonly TechnologyRepository _technologyService;
        private readonly ProductRepository _productService;
        //private readonly IProductPhotoService _productPhotoService;
        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public TechnologyController(IMapper mapper)
        {
            _technologyService = new TechnologyRepository();
            _productService = new ProductRepository();
            //_productPhotoService = productPhotoService;
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;

        }
       
        #region  Technology

        [HttpGet]
        public ActionResult Index(int? page, int? productId, string keyword)
        {
            var vm = new TechnologyListVM()
            {
                ProductId = productId ?? 0,
                PageIndex = page ?? 1,
                PageSize = SettingsManager.Product.PageSize,
                Keyword = keyword
            };
            int totalCount = 0;
            var list = _technologyService.GetListPagedItems(vm.PageIndex, vm.PageSize, vm.ProductId, vm.Keyword, out totalCount);
           // var dto = _mapper.Map<List<Technology>, List<TechnologyVM>>(list);

            vm.TotalCount = totalCount;

            var productList = _productService.GetItems().OrderBy(c => c.ProductName).ToList();
            foreach(var item in list)
            {
                item.Product = productList.FirstOrDefault(m=>m.Id==item.ProductId);
            }

            ViewBag.Products = new SelectList(productList, "Id", "ProductName");
          
            vm.Technologies = new StaticPagedList<Technology>(list, vm.PageIndex, vm.PageSize, vm.TotalCount);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(vm);


        }




        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/ProductSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        public ActionResult Add()
        {
            TechnologyIM Technology = new TechnologyIM();
            Technology.Active = true;

            var productList = _productService.GetItems().OrderBy(c => c.ProductName).ToList();
            ViewBag.Products = new SelectList(productList, "Id", "ProductName");


            return View(Technology);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(TechnologyIM Technology)
        {
           

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var newTechnology = _mapper.Map<TechnologyIM, Technology>(Technology);
                newTechnology.CreatedBy = Site.CurrentUserName;
                newTechnology.CreatedDate = DateTime.Now;

                _technologyService.Create(newTechnology);


                var pageMeta = new PageMeta()
                {
                    ObjectId = newTechnology.Id.ToString(),
                    Title = string.IsNullOrEmpty(Technology.Title) ? $"{Technology.Title}_{Technology.EnglishTitle}" : Technology.Title,
                    Keyword = Technology.Keywords,
                    Description = Technology.SEODescription,
                    ModelType = (short)ModelType.TECHNOLOGY
                };
                _pageMetaService.Create(pageMeta);


                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Technology));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }



        }

        [HttpGet]
        public ActionResult Edit(int id)
        {

            var vTechnology = _technologyService.GetById(id);
            if (vTechnology == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var editTechnology = _mapper.Map<Technology, TechnologyIM>(vTechnology);


            var pageMeta = _pageMetaService.GetPageMeta(DAL.Dapper.Model.ModelType.TECHNOLOGY, editTechnology.Id.ToString());
            if (pageMeta != null)
            {
                editTechnology.Title = pageMeta.Title;
                editTechnology.Keywords = pageMeta.Keyword;
                editTechnology.SEODescription = pageMeta.Description;
            }

            var productList = _productService.GetItems().OrderBy(c => c.ProductName).ToList();
            ViewBag.Products = new SelectList(productList, "Id", "ProductName");

            //ViewBag.Categories = GetCategoryList();
            return View(editTechnology);


        }



        [HttpPost]

        [ValidateAntiForgeryToken]
        public JsonResult Edit(TechnologyIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


            try
            {
                var editTechnology = _technologyService.GetById(vm.Id);
                editTechnology.Title = vm.Title;
                editTechnology.EnglishTitle = vm.EnglishTitle;
                editTechnology.ImagesURL = vm.ImagesURL;
                editTechnology.Importance = vm.Importance;
                editTechnology.Body = vm.Body;
                editTechnology.ProductId = vm.ProductId;

                editTechnology.UpdatedBy = Site.CurrentUserName;
                editTechnology.UpdatedDate = DateTime.Now;
                _technologyService.Update(editTechnology);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.TECHNOLOGY, editTechnology.Id.ToString());
                pageMeta = pageMeta ?? new PageMeta();


                pageMeta.ObjectId = editTechnology.Id.ToString();
                pageMeta.Title = vm.Title;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (short)ModelType.TECHNOLOGY;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Technology));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Technology vTechnology = _technologyService.GetById(id);

            try
            {
                vTechnology.Active = !vTechnology.Active;
                _technologyService.Update(vTechnology);

                var vm = _mapper.Map<Technology>(vTechnology);
                AR.Data = RenderPartialViewToString("_TechnologyItem", vm);

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Technology));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Technology vTechnology = _technologyService.GetById(id);

            if (vTechnology == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _technologyService.Delete(vTechnology);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Technology));
            return Json(AR, JsonRequestBehavior.DenyGet);


        }


        [HttpPost]
        public ActionResult UpLoadImages(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;

            string dir = "/Uploads/Images/Technology";
            string localPath = HostingEnvironment.MapPath(dir);
            // string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Uploads");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }

            string ex = Path.GetExtension(file.FileName);
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
           

            var orgUrl = Path.Combine(localPath, filePathName);           
            file.SaveAs(orgUrl);
          

            return Json(new
            {
                jsonrpc = "2.0",
                id = id,
                fileName = dir + "/" + filePathName
            });

        }
        [HttpPost]
        public ActionResult RemoveImage(string img)
        {
            try
            {
                string dir = "/Uploads/Images/Technology";
                string localPath = HostingEnvironment.MapPath(dir);
                var orgUrl = Path.Combine(localPath, img);
               

                if (System.IO.File.Exists(orgUrl))
                {
                    System.IO.File.Delete(orgUrl);
                }
              
                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        /// <summary>
        /// 创建索引目录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CreateIndex()
        {
            try
            {
                var list = _technologyService.GetActiveItems().Select(m => new SearchData
                {
                    Id = $"Technology{m.Id}",
                    Name = m.Title,
                    Description = StringHelper.StripTagsCharArray(m.Body),
                    ImageUrl = string.IsNullOrEmpty(m.ImagesURL)? string.Empty : m.ImagesURL.Split('|').FirstOrDefault(),
                    Url = $"{SettingsManager.Site.SiteDomainName}/product/technology/{m.Id}"
                }).ToList();

                GoLucene.AddUpdateLuceneIndex(list);

                AR.SetSuccess(String.Format(Messages.AlertActionSuccess, EntityNames.Technology));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        #endregion
    }
}